package com.leyou.item.controller;

import com.leyou.common.pojo.PageResult;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.entity.Sku;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.service.GoodsService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
public class GoodsController {
    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private GoodsService goodsService;

    @Scheduled(fixedDelay = 1200000)
    public void cleanJob() {
        //获取锁即锁定当前调用的订单微服务
        RLock rLock = redissonClient.getLock("lock");
        boolean tryLock = rLock.tryLock();
        if (!tryLock) {
            log.info("获取锁失败，停止定时任务");
            return;
        }
        try {
            log.info("获取锁成功，执行定时任务");
            goodsService.clean();
        } catch (Exception e) {
            log.error("定时任务执行异常");
        } finally {
            rLock.unlock();
            log.info("清理超时未支付订单的定时任务执行成功");
        }
    }

    @GetMapping("/echo2")
    public String feignEcho(HttpServletRequest request) {
        return goodsService.echo(request);
    }

    /**
     * 分页查询Spu
     */
    @GetMapping("/spu/page")
    public ResponseEntity<PageResult<SpuDTO>> spuPageQuery(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                                           @RequestParam(value = "rows", defaultValue = "5") Integer rows,
                                                           @RequestParam(value = "key", required = false) String key,
                                                           @RequestParam(value = "saleable", required = false) Boolean saleable) {
        PageResult<SpuDTO> pageResult = goodsService.spuPageQuery(page, rows, key, saleable);
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 保存商品
     */
    @PostMapping("/goods")
    public ResponseEntity<Void> saveGoods(@RequestBody SpuDTO spuDTO) {
        goodsService.saveGoods(spuDTO);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 商品上下架
     */
    @PutMapping("/spu/saleable")
    public ResponseEntity<Void> updateSaleable(@RequestParam("id") Long id,
                                               @RequestParam("saleable") Boolean saleable) {
        goodsService.updateSaleable(id, saleable);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 根据spuId查询sku集合
     */
    @GetMapping("/sku/of/spu")
    public ResponseEntity<List<Sku>> findSkusBySpuId(@RequestParam("id") Long id) {
        List<Sku> skus = goodsService.findSkusBySpuId(id);
        return ResponseEntity.ok(skus);
    }

    /**
     * 根据id查询SpuDetail对象
     */
    @GetMapping("/spu/detail")
    public ResponseEntity<SpuDetail> findSpuDetailById(@RequestParam("id") Long id) {
        SpuDetail spuDetail = goodsService.findSpuDetailById(id);
        return ResponseEntity.ok(spuDetail);
    }

    /**
     * 根据spuId查询SpuDTO对象
     */
    @GetMapping("/spu/{id}")
    public ResponseEntity<SpuDTO> findSpuDTOBySpuId(@PathVariable("id") Long id) {
        SpuDTO spuDTO = goodsService.findSpuDTOBySpuId(id);
        return ResponseEntity.ok(spuDTO);
    }

    /**
     * 根据skuid的集合批量查询sku对象集合
     */
    @GetMapping("/sku/list")
    public ResponseEntity<List<Sku>> findSkusByIds(@RequestParam("ids") List<Long> ids) {
        List<Sku> skus = goodsService.findSkusByIds(ids);
        return ResponseEntity.ok(skus);
    }

    /**
     * 减库存
     */
    @PutMapping("/stock/minus")
    public ResponseEntity<Void> minusStock(@RequestBody Map<Long, Integer> paramMap) {
        goodsService.minusStock(paramMap);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

}